import datetime, pypinyin, re, sys
sort_dict = lambda d: sorted(d.items(), key=lambda a: pypinyin.pinyin(a[0], style=pypinyin.Style.TONE3))
location = sys.argv[1]
year = datetime.date.today().year - 1
filename_head = f'{location}年鉴{year}'
department_count = {}
with open(f'{filename_head}图片使用索引记录.txt') as img_file:
    for img_row in img_file:
        img_name, img_caption, img_page = img_row.split()
        department = re.search('（([^）]+)供图(?:摄于\d+年)?）', img_caption)[1]
        if startswith_location := re.fullmatch(f'{location}(?:街道|镇)?(.+)', department):
            department = startswith_location[1]
        department_count[department] = 1 + department_count.get(department, 0)
sorted_department_count = sort_dict(department_count)
print(f'```mermaid\nxychart-beta horizontal\ntitle"{filename_head}图片数"')
print(f'''x-axis[{','.join(f'"{s[0]}"'for s in sorted_department_count)}]''')
print(f'y-axis 0-->{max(s[1]for s in sorted_department_count)}')
print(f"bar[{','.join(str(s[1])for s in sorted_department_count)}]")
print('```\n\n---\n')
outline = {}
with open(f'{filename_head}大纲.txt') as outline_file:
    for outline_row in outline_file:
        outline_row = outline_row[:-1]
        if re.match('\S', outline_row):
            outline[leimuming := outline_row] = {}
        if re.match(' \S', outline_row):
            outline[leimuming][fenmuming := outline_row[1:]] = [] 
        if re.match('  \S', outline_row):
            outline[leimuming][fenmuming] += outline_row[2:],
schedule = {}
with open(f'{filename_head}进度.txt') as schedule_file:
    for schedule_row in schedule_file:
        schedule_row = schedule_row[:-1]
        if '第三方编辑' != schedule_row and re.match('\S', schedule_row):
            schedule[department := schedule_row] = 0
        if leimus := re.match(' (.+)类目(?:$|。)', schedule_row):
            schedule[department] += sum(sum(len(v)for v in outline[l].values())for l in leimus[1].split('、'))
        if fenmus := re.match(' (.+)类目：(.+)分目(?:$|。)', schedule_row):
            schedule[department] += sum(len(outline[fenmus[1]][f])for f in fenmus[2].split('、'))
        if tiaomus := re.match(' .+类目：.+分目：([^【】]+)条目(?:$|。)', schedule_row):
            schedule[department] += len(tiaomus[1].split('、'))
        if nontiaomus := re.match(' (.+)类目：(.+)分目：非【(.+)】条目(?:$|。)', schedule_row):
            schedule[department] += len(outline[nontiaomus[1]][nontiaomus[2]]) - len(nontiaomus[3].split('】【'))
sorted_schedule = sort_dict(schedule)
print(f'```mermaid\nxychart-beta horizontal\ntitle"{filename_head}条目数"')
print(f'''x-axis[{','.join(f'"{s[0]}"'for s in sorted_schedule)}]''')
print(f'y-axis 0-->{max(s[1]for s in sorted_schedule)}')
print(f"bar[{','.join(str(s[1])for s in sorted_schedule)}]")
print('```')
